package org.fxd.zweixin.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 功能:zip压缩、解压(支持中文文件名) 说明:本程序通过使用Apache
 * Ant里提供的zip工具org.apache.tools.zip实现了zip压缩和解压功能. 解决了由于java.util.zip包不支持汉字的问题。
 * 使用java.util.zip包时,当zip文件中有名字为中文的文件时, 就会出现异常:"Exception in thread "main "
 * java.lang.IllegalArgumentException at
 * java.util.zip.ZipInputStream.getUTF8String(ZipInputStream.java:285) 注意:
 * 1、使用时把ant.jar放到classpath中,程序中使用import org.apache.tools.zip.*; 2、Apache Ant
 * 下载地址:[url]http://ant.apache.org/[/url] 3、Ant ZIP
 * API:[url]http://www.jajakarta.org/ant/ant-1.6.1/docs/mix/manual/api/org/apache/tools/zip/[/url]
 * 4、本程序使用Ant 1.7.1 中的ant.jar
 *
 * 仅供编程学习参考.
 *
 * @author Winty
 * @date 2008-8-3
 * @Usage: 压缩:java AntZip -zip "directoryName" 解压:java AntZip -unzip
 *         "fileName.zip"
 */

public class AntZip {

	// 压缩文件夹内的文件
		public static void doZip(List<File> filelist, File zipFile) {// zipDirectoryPath:需要压缩的文件夹名
			try {
				ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
				
				for (File fileName : filelist) {
					zipOut.putNextEntry(new ZipEntry(fileName.getName()));

					byte[] readedBytes = new byte[10240];
					int len = 0;
					FileInputStream fileIn = new FileInputStream(fileName);
					while ((len = fileIn.read(readedBytes)) != -1) {
						zipOut.write(readedBytes, 0, len);
					}
					fileIn.close();
					zipOut.closeEntry();
				}
				zipOut.close();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}

		
	// 压缩文件夹内的文件
	public static void doZip2(List<File> filelist, File zipFile) {// zipDirectoryPath:需要压缩的文件夹名
		try {
			ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
			
			for (File fileName : filelist) {
				zipOut.putNextEntry(new ZipEntry(fileName.getAbsolutePath()));

				byte[] readedBytes = new byte[10240];
				int len = 0;
				FileInputStream fileIn = new FileInputStream(fileName);
				while ((len = fileIn.read(readedBytes)) != -1) {
					zipOut.write(readedBytes, 0, len);
				}
				fileIn.close();
				zipOut.closeEntry();
			}
			zipOut.close();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

}
